package com.alibaba.citrus.cr.unified.inventory.repository.impl;

import com.alibaba.citrus.cr.unified.inventory.repository.InvoiceOrderWriteRepository;
import com.alibaba.citrus.cr.common.annotation.EpochTransactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.crunifiedinventory.api.invoiceorderread.service.InvoiceOrderReadService;
import com.epoch.app.crunifiedinventory.domain.invoiceorder.dto.CreateInvoiceOrderResponse;
import com.epoch.app.crunifiedinventory.domain.invoiceorder.dto.DeleteInvoiceOrderRequest;
import com.epoch.app.crunifiedinventory.domain.invoiceorder.model.InvoiceOrder;
import com.epoch.app.crunifiedinventory.domain.invoiceorder.service.InvoiceOrderService;
import com.epoch.app.crunifiedinventory.domain.invoiceorderdetail.dto.DeleteInvoiceOrderDetailRequest;
import com.epoch.app.crunifiedinventory.domain.invoiceorderdetail.model.InvoiceOrderDetail;
import com.epoch.app.crunifiedinventory.domain.invoiceorderdetail.service.InvoiceOrderDetailService;
import com.epoch.app.crunifiedinventory.model.dto.InvoiceOrderSearchRequest;
import com.epoch.app.crunifiedinventory.model.dto.InvoiceOrderSearchResponse;
import com.epoch.app.crunifiedinventory.sdo.InvoiceOrderDetailSDO;
import com.epoch.app.crunifiedinventory.sdo.InvoiceOrderSDO;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author zhangguoqing.zgq
 * @date 2021/10/16
 */
@Component
public class InvoiceOrderWriteRepositoryImpl implements InvoiceOrderWriteRepository {
    @Resource
    private InvoiceOrderService invoiceOrderService;

    @Resource
    private InvoiceOrderDetailService invoiceOrderdetailService;

//    @Resource
//    private InvoiceOrderReadService invoiceOrderReadService;

    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public String create(InvoiceOrderSDO invoiceOrderSDO) {
//        InvoiceOrderSearchRequest invoiceOrderSearchRequest = new InvoiceOrderSearchRequest();
//        invoiceOrderSearchRequest.setInvoiceOrderId(invoiceOrderSDO.getInvoiceOrderId());
//        Result<InvoiceOrderSearchResponse> search = invoiceOrderReadService.search(invoiceOrderSearchRequest);
//        if (Objects.nonNull(search)&&Objects.nonNull(search.getResult())&&(Objects.nonNull(search.getResult().getDetail())|| CollectionUtils.isNotEmpty(search.getResult().getList()))){
//            return invoiceOrderSDO.getInvoiceOrderId();
//        }
        InvoiceOrder invoiceOrder = convertInvoiceOrderSDO2InvoiceOrder(invoiceOrderSDO);
        CreateInvoiceOrderResponse response = invoiceOrderService.createInvoiceOrder(invoiceOrder);
        invoiceOrderSDO.getDetailList().forEach(detail -> {
            InvoiceOrderDetail invoiceOrderDetail = convertInvoiceOrderDetailSDO2InvoiceOrderDetail(detail);
            invoiceOrderDetail.setInvoiceOrdeId(Long.valueOf(response.getLastInsertId()));

            invoiceOrderdetailService.createInvoiceOrderDetail(invoiceOrderDetail);
        });

        return response.getLastInsertId();
    }

    private InvoiceOrder convertInvoiceOrderSDO2InvoiceOrder(InvoiceOrderSDO invoiceOrderSDO) {
        InvoiceOrder invoiceOrder = JSONObject.parseObject(JSON.toJSONString(invoiceOrderSDO),
                InvoiceOrder.class);

        invoiceOrder.setInvoiceOrderId(invoiceOrderSDO.getInvoiceOrderId());
        invoiceOrder.setReverseInvoiceId(invoiceOrderSDO.getReverseInvoiceId());
        invoiceOrder.setType(invoiceOrderSDO.getType());
        invoiceOrder.setSaleOrganizationCode(invoiceOrderSDO.getSaleOrganizationCode());
        invoiceOrder.setDeliveryOrderId(invoiceOrderSDO.getDeliveryOrderId());
        invoiceOrder.setSourceOrderId(invoiceOrderSDO.getSourceOrderId());
        invoiceOrder.setSapGenerateTime(invoiceOrderSDO.getSapGenerateTime());
        invoiceOrder.setCreateDate(invoiceOrderSDO.getCreateDate());
        invoiceOrder.setCompanyCode(invoiceOrderSDO.getCompanyCode());
        invoiceOrder.setFeature(getFeatureStr(invoiceOrderSDO.getFeature()));
        invoiceOrder.setCreator(invoiceOrderSDO.getCreator());
        // 源单创建时间
        invoiceOrder.setSourceOrderCreateTime(invoiceOrderSDO.getSourceOrderCreateTime());

        return invoiceOrder;
    }

    private InvoiceOrderDetail convertInvoiceOrderDetailSDO2InvoiceOrderDetail(
            InvoiceOrderDetailSDO invoiceOrderDetailSDO) {
        InvoiceOrderDetail invoiceOrderDetail = JSONObject.parseObject(JSON.toJSONString(invoiceOrderDetailSDO),
                InvoiceOrderDetail.class);
        invoiceOrderDetail.setInvoiceOrderId(invoiceOrderDetailSDO.getInvoiceOrderId());
        if (StringUtils.isNotBlank(invoiceOrderDetailSDO.getOrderLineId())) {
            invoiceOrderDetail.setOrderLineId(Integer.valueOf(invoiceOrderDetailSDO.getOrderLineId()));
        }
        invoiceOrderDetail.setSaleOrganizationCode(invoiceOrderDetailSDO.getSaleOrganizationCode());
        invoiceOrderDetail.setDeliveryOrderId(invoiceOrderDetailSDO.getDeliveryOrderId());
        invoiceOrderDetail.setSourceOrderId(invoiceOrderDetailSDO.getSourceOrderId());
        invoiceOrderDetail.setSapGeneratorTime(invoiceOrderDetailSDO.getSapGenerateTime());
        invoiceOrderDetail.setScItemId(invoiceOrderDetailSDO.getScItemId());
        invoiceOrderDetail.setTitle(invoiceOrderDetailSDO.getTitle());
        invoiceOrderDetail.setPrice(invoiceOrderDetailSDO.getPrice());
        invoiceOrderDetail.setQuantity(invoiceOrderDetailSDO.getQuantity());
        invoiceOrderDetail.setSubTotalAmount(invoiceOrderDetailSDO.getSubTotalAmount());
        invoiceOrderDetail.setFeature(getFeatureStr(invoiceOrderDetailSDO.getFeature()));
        // 源单创建时间
        invoiceOrderDetail.setSourceOrderCreateTime(invoiceOrderDetailSDO.getSourceOrderCreateTime());

        // 交货单行号
        invoiceOrderDetail.setDeliveryOrderLineId(invoiceOrderDetailSDO.getDeliveryOrderLineId());
        // 销售订单行号
        invoiceOrderDetail.setSalesOrderLineId(invoiceOrderDetailSDO.getSalesOrderLineId());
        invoiceOrderDetail.setCompanyCode(invoiceOrderDetailSDO.getCompanyCode());
        return invoiceOrderDetail;
    }

    public String getFeatureStr(Map<String, String> feature) {
        StringBuilder sb = new StringBuilder();
        if (MapUtils.isEmpty(feature)) {
            return sb.toString();
        }
        for (Map.Entry<String, String> entry : feature.entrySet()) {
            sb.append(entry.getKey()).append(":").append(entry.getValue());
        }
        return sb.toString();
    }
    @Override
    @EpochTransactional(appCode="bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public String update(InvoiceOrderSDO invoiceOrderSDO) {
        DeleteInvoiceOrderRequest deleteInvoiceOrderRequest = new DeleteInvoiceOrderRequest();
        deleteInvoiceOrderRequest.setId(invoiceOrderSDO.getId());
        invoiceOrderService.deleteInvoiceOrder(deleteInvoiceOrderRequest);
        DeleteInvoiceOrderDetailRequest deleteInvoiceOrderDetailRequest = new DeleteInvoiceOrderDetailRequest();
        for (Long id: invoiceOrderSDO.getInvoiceOrderDetailIds()) {
            deleteInvoiceOrderDetailRequest.setId(id);
            invoiceOrderdetailService.deleteInvoiceOrderDetail(deleteInvoiceOrderDetailRequest);
        }
        InvoiceOrder invoiceOrder = convertInvoiceOrderSDO2InvoiceOrder(invoiceOrderSDO);
        CreateInvoiceOrderResponse response = invoiceOrderService.createInvoiceOrder(invoiceOrder);
        invoiceOrderSDO.getDetailList().forEach(detail -> {
            InvoiceOrderDetail invoiceOrderDetail = convertInvoiceOrderDetailSDO2InvoiceOrderDetail(detail);
            invoiceOrderDetail.setInvoiceOrdeId(Long.valueOf(response.getLastInsertId()));

            invoiceOrderdetailService.createInvoiceOrderDetail(invoiceOrderDetail);
        });

        return response.getLastInsertId();
    }
}
